<?php
namespace logic\wechat\delivery;
use model\ShopStore;
use model\ShopStoreDelivery;
use model\ShopWatercardOrder;
use think\Config;
use think\Cookie;

/**
 * User: lsx
 * Date: 2017/5/20
 * Time: 14:54
 * Progress:0%
 */
class LOrder
{
    private $order;
    private $aid;
    private $store;
    private $shopStoreDelivery;
    public function __construct()
    {
        $this->order=new ShopWatercardOrder();
        $this->store=new ShopStore();
        $this->shopStoreDelivery=new ShopStoreDelivery();
        $this->aid = Cookie::get(Config::get('const.cookie_name_wechat'));
    }
    public function logic_index(){
        $store_id=$this->shopStoreDelivery->where(['account_id'=>$this->aid])->value('store_id');
        $order=$this->order->alias('o')
            ->join('shop_user_watercard u','u.id=o.user_card_id','left')
            ->join('shop_watercard w','w.id=u.card_id','left')
            ->join('shop_goods g','g.id=w.goods_id','left')
            ->field("o.*,g.name as goods_name")->where(['o.store_id'=>$store_id,'o.order_status'=>'000'])->order('o.order_time desc')->select();
        return $order;
    }

    public function logic_detail($id){
        $order=$this->order->alias('o')
            ->join('shop_user_watercard u','u.id=o.user_card_id','left')
            ->join('account a','a.id=o.account_id','left')
            ->join('shop_watercard w','w.id=u.card_id','left')
            ->join('shop_goods g','g.id=w.goods_id','left')
            ->field("o.*,a.name as delivery_name,g.name as goods_name,(case 
                when (order_status = 000 ) then '等待配送' 
                when (order_status = 110 or order_status = 210 ) then '配送中'
                when (order_status = 111 or order_status = 211 ) then '订单完成'
                else order_status end)
                as 'order_status_ch'
            ")->where(['o.id'=>$id])->find();
        return $order;
    }

    public function logic_delivery_order_submit($id){
        $item=$this->order->where(['id'=>$id])->find();
        if(!$item){
            return array(
                'success'=>false,
                'message'=>'数据出错3，请稍后再试'
            );
        }
        if($item->flag_delivery ==1){
            return array(
                'success'=>false,
                'message'=>'订单正在配送',
                'code'=>-1
            );
        }
        $update_data=array(
          'delivery_time'=>time(),
          'flag_delivery'=>1,
          'order_status'=>110,
          'delivery_id'=>$this->aid
        );
        $res=$this->order->save($update_data,['id'=>$id]);
        if($res){
            return array(
                'success'=>true,
                'message'=>'操作成功',
                'url'=>url('User/my_delivery')
            );
        }else{
            return array(
                'success'=>false,
                'message'=>'数据出错3，请稍后再试'
            );
        }
    }

}